package day11.gec.事务;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import day11.gec.utils.JDBCUtil3;

public class TestAccountDemo {
	public static void main(String[] args) {
		Connection conn = JDBCUtil3.getConnection();
		ResultSet rs = null;
		Statement st = null;
		try {
			//设置为手动提交事务
			conn.setAutoCommit(false);
			
			st = conn.createStatement();
			//检查无忌帐上是否大于1000
			String sql = "select balance from account where balance > 1000 and id = 1";
			
			rs = st.executeQuery(sql);
			//判断
			if(!rs.next()) {
				throw new RuntimeException("无忌，你给我记着，分手 ");
			}
			
			//给无忌的帐户上减去1000
			sql = "update account set balance = balance -1000 where id = 1";
			//执行
			st.executeUpdate(sql);
			
			//引发异常
			//int i = 5/0; //遇到异常，会被捕获，然后在catch里面回滚事务
			
			//给无忌的帐户上加上1000
			sql = "update account set balance = balance + 1000 where id = 2";
			st.executeUpdate(sql);
			
			//代码运行到这里那可以提交事务
			conn.commit();
		} catch (Exception e) {
			e.printStackTrace();
			try {
			    //回滚事务
				conn.rollback();
			} catch (SQLException e1) {
				e1.printStackTrace();
			} 
		}
	}
}
